﻿#include <QWebEngineView>
#include <QRandomGenerator>
#include "mainwindow.h"
#include "ui_MainWindow.h"


MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);

    QUrl lineChartPath = "file:///" + qApp->applicationDirPath() + "/file/line_chart.html";

    ui->webEngineView->load(QUrl(lineChartPath));

    timer = new QTimer(this);

    connect(ui->btnStart, &QPushButton::clicked, this, &MainWindow::on_btnStart_clicked);
    connect(ui->btnStop, &QPushButton::clicked, this, &MainWindow::on_btnStop_clicked);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateChart);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::on_btnStart_clicked() {
    if (timer) {
        if (!timer->isActive()) {
            timer->start(1000);
        }
    }
}


void MainWindow::on_btnStop_clicked() {
    if (timer) {
        if (timer->isActive()) {
            timer->stop();
        }
    }
}

void MainWindow::updateChart() {
    QStringList stringList;
    int size = 4;

    for (int i = 0; i < size; i++) {
        int randNum = QRandomGenerator::global()->bounded(100, 501);
        stringList.append(QString::number(randNum));
    }

    QString str = stringList.join(", ");

    QString script = QString("updateChart('%1');").arg(str);

    ui->webEngineView->page()->runJavaScript(script);
}


